import { defineStore } from 'pinia';
import { KeepAliveState } from '@/stores/interface';

export const useKeepAliveStore = defineStore({
  id: 'geeker-keepAlive',
  state: (): KeepAliveState => ({
    keepAliveName: [],
    componentCache: new Map(),
    tableCloseName: new Map(),
    cachePrefix: 'Wrapper_'
  }),
  actions: {
    // Add KeepAliveName
    async addKeepAliveName(fullName: string) {
      if (!this.keepAliveName.includes(fullName)) {
        this.keepAliveName.push(fullName);
        if (this.tableCloseName.has(fullName)) {
          this.tableCloseName.delete(fullName);
        }
      }
    },
    // Remove KeepAliveName
    async removeKeepAliveName(tabItem) {
      const fullName = this.cachePrefix + tabItem.name + tabItem.meta.flag;
      this.keepAliveName = this.keepAliveName.filter(item => item !== fullName);
      this.tableCloseName.set(fullName, true);
      this.componentCache.delete(tabItem.name + tabItem.meta.flag);
    },
    // Set KeepAliveName
    async setKeepAliveName(keepAliveName: string[] = []) {
      this.keepAliveName = keepAliveName;
    }
  }
});
